package com.xiaoke.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xiaoke.entity.Comment;
import com.xiaoke.entity.CommentPicture;
import com.xiaoke.mapper.CommentMapper;
import com.xiaoke.mapper.CommentPictureMapper;
import com.xiaoke.service.CommentService;
import com.xiaoke.utils.SnowflakeIdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;
import java.util.Map;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private CommentPictureMapper commentPictureMapper;
    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;
    @Override
    @Transactional(readOnly = false)
    public void insert(@RequestBody Comment comment, String images) {
        comment.setId(String.valueOf(snowflakeIdWorker.nextId()));
        commentMapper.insert(comment);

        CommentPicture commentPicture = new CommentPicture();
        commentPicture.setCommentId(comment.getId());
        commentPicture.setId(String.valueOf(snowflakeIdWorker.nextId()));
        commentPicture.setPicUrl(images);
        commentPictureMapper.insert(commentPicture);
    }

    @Override
    public Integer countByGoods(String goodsId) {
        return commentMapper.countByGoods(goodsId);
    }

    @Override
    public List<Map<String, Object>> findByGoodsAndPic(String goodsId, Integer pageNum, Integer pageSize,Integer showType) {
        PageHelper.startPage(pageNum,pageSize,true,false);
        if(showType == 0){
            //全部
            Page<Map<String, Object >> page = commentMapper.findByGoods(goodsId);
            List<Map<String, Object>> allComment = addCommentPic(page);
            return allComment;
        }
        if(showType == 1){
            Page<Map<String, Object >> page = commentMapper.findByGoodsAndPic(goodsId);
            List<Map<String, Object>> picComment = addCommentPic(page);
            return picComment;
        }

        return null;
    }

    private List<Map<String, Object>> addCommentPic(Page<Map<String, Object>> page) {
        List<Map<String, Object>> picComment = page.getResult();
        for (Map c: picComment ) {
            List<String> pic_list = commentPictureMapper.findByComment((String) c.get("id"));
            c.put("pic_list",pic_list);
        }
        return picComment;
    }

    @Override
    public Integer countByGoodsPic(String goodsId) {
        return commentMapper.countByGoodsPic(goodsId);
    }
}
